package com.xywh.wanandroid.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.xywh.wanandroid.data.model.bean.CollectArticlesData
import com.xywh.wanandroid.data.repository.WanAndroidRepository
import com.xywh.wanandroid.ext.requestCompose
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.network.apiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import javax.inject.Inject

@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class CollectComposeViewModel @Inject constructor(
    val repository: WanAndroidRepository
) : BaseViewModel() {
    var collectList = repository.fetchCollectDataList().cachedIn(viewModelScope)

    private val updateCollectListData: MutableStateFlow<Int> = MutableStateFlow(0)

    val collectListLiveData: Flow<PagingData<CollectArticlesData>> =
        updateCollectListData.flatMapLatest {

            Log.e("updateData.value===", "flatMapLatest")
            repository.fetchCollectDataList()

        }

    init {
        viewModelScope.launch {
            updateCollectListData.collect {
//                updateData.value.plus(1)
                Log.e("updateData.value===", "${updateCollectListData.value}")
            }
        }
    }

    private fun updateCollectListData() {
        updateCollectListData.value = updateCollectListData.value.plus(1)
    }

    fun removeCollectArticle(id: Int, originId: Int, updateMainScreenCollectListData: () -> Unit) {
        requestCompose(
            { apiService.removeCollectArticle(id, originId) },
            {
                showToastMsg("取消收藏成功")
                updateCollectListData()
                updateMainScreenCollectListData.invoke()
            }, {
                showToastMsg(it.errorMsg)
            },
            true,
            "取消收藏中..."
        )
    }
}